from flask import Flask, render_template, request, jsonify, send_file
import os
import json
import uuid
import threading
from datetime import datetime

# 添加项目根目录到Python路径
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from services.podcast_service import PodcastService
from config.settings import Config
from factories.character_factory import CharacterFactory

app = Flask(__name__, 
            template_folder='templates',
            static_folder='static')

# 存储任务状态的字典
tasks = {}

class PodcastGenerationTask:
    def __init__(self, task_id, topic, characters):
        self.task_id = task_id
        self.topic = topic
        self.characters = characters
        self.status = "started"
        self.progress = 0
        self.result_text = ""
        self.result_audio_files = []
        self.created_at = datetime.now()
        self.completed_at = None

    def to_dict(self):
        return {
            'task_id': self.task_id,
            'topic': self.topic,
            'characters': [c.name for c in self.characters],
            'status': self.status,
            'progress': self.progress,
            'result_text': self.result_text,
            'result_audio_files': self.result_audio_files,
            'created_at': self.created_at.isoformat(),
            'completed_at': self.completed_at.isoformat() if self.completed_at else None
        }

@app.route('/')
def index():
    """主页"""
    return render_template('index.html')

@app.route('/generate', methods=['POST'])
def generate_podcast():
    """生成播客"""
    data = request.get_json()
    topic = data.get('topic', '')
    mode = data.get('mode', 'single')
    
    if not topic:
        return jsonify({'error': 'Topic is required'}), 400
    
    # 创建任务
    task_id = str(uuid.uuid4())
    character_factory = CharacterFactory()
    characters = character_factory.create_multiple_characters(Config.CHARACTER_CONFIGS)
    
    task = PodcastGenerationTask(task_id, topic, characters)
    tasks[task_id] = task
    
    # 在后台线程中执行生成任务
    thread = threading.Thread(target=execute_generation_task, args=(task, mode))
    thread.start()
    
    return jsonify({'task_id': task_id})

@app.route('/progress/<task_id>')
def get_progress(task_id):
    """获取任务进度"""
    task = tasks.get(task_id)
    if not task:
        return jsonify({'error': 'Task not found'}), 404
    
    return jsonify(task.to_dict())

@app.route('/audio/<filename>')
def get_audio(filename):
    """获取音频文件"""
    audio_path = os.path.join('output', filename)
    if os.path.exists(audio_path):
        return send_file(audio_path)
    else:
        return jsonify({'error': 'Audio file not found'}), 404

def execute_generation_task(task, mode):
    """执行播客生成任务"""
    try:
        # 更新进度
        task.status = "generating_text"
        task.progress = 25
        
        # 初始化服务
        podcast_service = PodcastService(
            llm_config=Config.LLM_CONFIG,
            tts_config=Config.TTS_CONFIG
        )
        
        # 生成播客内容
        if mode == "multi" and len(task.characters) >= 2:
            # 多角色播客
            task.result_text = "正在生成多角色播客..."
            audio_segments = podcast_service.generate_multi_character_podcast(
                task.topic,
                task.characters[:2]
            )
            
            # 保存音频文件
            os.makedirs('output', exist_ok=True)
            audio_files = []
            for i, segment in enumerate(audio_segments):
                filename = f"{task.task_id}_{i}.mp3"
                filepath = os.path.join('output', filename)
                
                # 保存音频数据到文件
                with open(filepath, 'wb') as f:
                    f.write(segment['audio'])
                
                audio_files.append(filename)
            
            task.result_audio_files = audio_files
            task.result_text = "多角色播客生成完成"
        else:
            # 单角色播客
            task.result_text = "正在生成单角色播客..."
            character = task.characters[0] if task.characters else None
            if character:
                audio_data = podcast_service.generate_single_character_podcast(
                    task.topic,
                    character
                )
                
                # 保存音频文件
                os.makedirs('output', exist_ok=True)
                filename = f"{task.task_id}.mp3"
                filepath = os.path.join('output', filename)
                
                with open(filepath, 'wb') as f:
                    f.write(audio_data)
                
                task.result_audio_files = [filename]
                task.result_text = "单角色播客生成完成"
            else:
                task.result_text = "未找到角色配置"
        
        # 更新任务状态
        task.status = "completed"
        task.progress = 100
        task.completed_at = datetime.now()
        
    except Exception as e:
        task.status = "failed"
        task.result_text = f"生成失败: {str(e)}"
        task.progress = 100

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)